package com.allwees.bs.c.module.sys.service.impl;

import com.allwees.bs.c.module.sys.entity.SysSequenceEntity;
import com.allwees.bs.c.module.sys.repository.SysSequenceRepository;
import com.allwees.bs.c.module.sys.service.ISysSequenceService;
import com.allwees.core.cache.lock.RedisLock;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Service
public class SysSequenceServiceImpl implements ISysSequenceService{
    private static final Logger log = LoggerFactory.getLogger(SysSequenceServiceImpl.class);

    @Autowired
    private SysSequenceRepository sysSequenceRepository;

    @Autowired
    private RedisLock redisLock;

    @Override
    @Transactional
    public Long getNext(String prefix) {
        // TODO 分布式锁
        RLock rLock = redisLock.lock(prefix, 3000, TimeUnit.MILLISECONDS);
        // 初始化
        SysSequenceEntity sysSequenceEntity = sysSequenceRepository.selectByPrefix(prefix);
        if(sysSequenceEntity == null){
            sysSequenceEntity = new SysSequenceEntity(prefix, 1L);
            sysSequenceRepository.save(sysSequenceEntity);
            return 1L;
        }

        sysSequenceRepository.updateCurrent(prefix);

        redisLock.unlock(rLock);

        return sysSequenceEntity.getCurrent() + 1L;
    }
}
